<template>
  <div class="app-container">
    <el-card>
      <!-- 标题 -->
      <div slot="header" class="clearfix">
        <span>学生学科竞赛获奖统计</span>
      </div>

      <!-- 选择器 -->
      <div class="selector-container">
        <!-- 专业输入 -->
        <el-autocomplete
          v-model="selectedMajorLabel"
          :fetch-suggestions="queryMajor"
          placeholder="请输入专业名称或ID"
          @select="handleMajorSelect"
        >
          <template #default="{ item }">
            <div class="autocomplete-item">{{ item.label }}</div>
          </template>
        </el-autocomplete>

        <!-- 班级输入 -->
        <el-autocomplete
          v-model="selectedClassLabel"
          :fetch-suggestions="queryClass"
          placeholder="请输入班级名称或ID"
          @select="handleClassSelect"
        >
          <template #default="{ item }">
            <div class="autocomplete-item">{{ item.label }}</div>
          </template>
        </el-autocomplete>

        <!-- 学生输入 -->
        <el-autocomplete
          v-model="selectedStudentLabel"
          :fetch-suggestions="queryStudent"
          placeholder="请输入学号或姓名"
          @select="handleStudentSelect"
        >
          <template #default="{ item }">
            <div class="autocomplete-item">{{ item.label }}</div>
          </template>
        </el-autocomplete>

        <!-- 查询按钮 -->
        <el-button type="primary" @click="fetchData">查询</el-button>
      </div>

      <!-- 数据展示 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else>
        <el-table
          :data="competitionData"
          border
          style="width: 100%"
          empty-text="暂无竞赛获奖数据"
        >
          <!-- 学生信息 -->
          <el-table-column prop="studentName" label="学生姓名" align="center" width="120" />

          <!-- 竞赛信息 -->
          <el-table-column prop="competitionName" label="竞赛名称" align="center" />

          <!-- 竞赛类型 -->
          <el-table-column prop="competitionType" label="竞赛类型" align="center" width="150">
            <template #default="scope">
              <el-tag size="small">{{ scope.row.competitionType }}</el-tag>
            </template>
          </el-table-column>

          <!-- 奖项等级 -->
          <el-table-column prop="awards" label="奖项等级" align="center" width="120" />

          <!-- 参赛人数 -->
          <el-table-column prop="entrants" label="参赛明细" align="center" width="100" />
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  getCompetitionByMajor,
  getCompetitionByClass,
  getCompetitionByStudent
} from '@/api/teacher'

export default {
  name: 'CompetitionStatistics',
  data() {
    return {
      // 映射表（自动生成）
      majorMapping: {}, // 中文名 => ID
      classMapping: {}, // 专业ID => 班级列表
      studentMapping: {}, // 班级ID => 学生列表

      // 展示用字段
      selectedMajorLabel: '', // 专业显示名
      selectedMajorValue: '', // 专业ID
      selectedClassLabel: '', // 班级显示名
      selectedClassValue: '', // 班级ID
      selectedStudentLabel: '', // 学生显示名
      selectedStudentValue: '', // 学号

      // 自动补全选项
      majorOptions: [],
      classOptions: [],
      studentOptions: [],

      // 表格数据
      competitionData: [],

      // 加载状态
      loading: false,

      // 辅助字段
      classDisplayNames: {} // 班级ID => 显示名
    }
  },
  created() {
    // 模拟原始数据输入（可以从接口获取）
    const rawMajorData = `
major1,college1,计科
major2,college1,AI
major3,college1,大数据
major4,college1,物联
major5,college1,通信
major6,college1,电子
major7,college1,计算机类
major8,college1,曙光
major9,college1,电信类
major10,college1,建筑类
    `.trim().split('\n')

    const rawClassData = `
class126,major1,计科2401班
class104,major1,计科2402班
class41,major1,计科2403班
class111,major1,计科2404班
class86,major2,AI2401班
class121,major2,AI2402班
    `.trim().split('\n')

    const rawStudentData = `

    `.trim().split('\n')

    // 自动生成映射表
    this.generateMappings(rawMajorData, rawClassData, rawStudentData)
  },
  methods: { // 自动生成映射关系
    generateMappings(majors, classes, students) {
      // 解析专业映射
      majors.forEach(line => {
        // eslint-disable-next-line no-unused-vars
        const [id, _, label] = line.split(',')
        this.$set(this.majorMapping, label.trim(), id.trim())
        this.majorOptions.push({ label: label.trim(), value: id.trim() })
      })
      // 解析班级映射
      classes.forEach(line => {
        const [classId, majorId, className] = line.split(',')
        if (!this.classMapping[majorId]) {
          this.$set(this.classMapping, majorId, [])
        }
        this.classMapping[majorId].push(classId.trim())

        if (!this.classDisplayNames) this.classDisplayNames = {}
        this.classDisplayNames[classId.trim()] = className.trim()
      })
      // 解析学生映射
      students.forEach(line => {
        const [studentId, classId] = line.split(',')
        if (!this.studentMapping[classId]) {
          this.$set(this.studentMapping, classId, [])
        }
        this.studentMapping[classId].push(studentId.trim())
      })
    },
    // 搜索建议 - 专业
    queryMajor(queryString, cb) {
      const results = this.majorOptions.filter(item =>
        item.label.includes(queryString) || item.value.includes(queryString)
      )
      cb(results)
    },
    // 搜索建议 - 班级
    queryClass(queryString, cb) {
      const results = this.classOptions.filter(item =>
        item.label.includes(queryString) || item.value.includes(queryString)
      )
      cb(results)
    },
    // 搜索建议 - 学生
    queryStudent(queryString, cb) {
      const results = this.studentOptions.filter(item =>
        item.label.includes(queryString) || item.value.includes(queryString)
      )
      cb(results)
    },
    // 选择专业
    handleMajorSelect(item) {
      const { label, value } = item
      this.selectedMajorLabel = label
      this.selectedMajorValue = value
      this.selectedClassLabel = ''
      this.selectedClassValue = ''
      this.selectedStudentLabel = ''
      this.selectedStudentValue = ''
      this.fetchClassOptions(value)
    },
    // 选择班级
    handleClassSelect(item) {
      const { label, value } = item
      this.selectedClassLabel = label
      this.selectedClassValue = value
      this.selectedStudentLabel = ''
      this.selectedStudentValue = ''
      this.fetchStudentOptions(value)
    },
    // 选择学生
    handleStudentSelect(item) {
      const { label, value } = item
      this.selectedStudentLabel = label
      this.selectedStudentValue = value
    },
    // 获取班级选项
    fetchClassOptions(majorId) {
      const classes = this.classMapping[majorId] || []
      this.classOptions = classes.map(id => ({
        label: this.classDisplayNames?.[id] || `${id}班`,
        value: id
      }))
    },
    // 获取学生选项
    fetchStudentOptions(classId) {
      const students = this.studentMapping[classId] || []
      this.studentOptions = students.map(id => ({
        label: `学号 ${id}`,
        value: id
      }))
    },
    // 请求数据
    async fetchData() {
      this.loading = true
      try {
        let response
        // 优先级：学生 > 班级 > 专业
        if (this.selectedStudentValue) {
          response = await getCompetitionByStudent(this.selectedStudentValue)
        } else if (this.selectedClassValue) {
          response = await getCompetitionByClass(this.selectedClassValue)
        } else if (this.selectedMajorValue) {
          response = await getCompetitionByMajor(this.selectedMajorValue)
        } else {
          this.$message.warning('请选择专业、班级或学生')
          this.loading = false
          return
        }
        if (response.success && Array.isArray(response.data)) {
          this.competitionData = response.data.map(item => ({
            ...item,
            awards: this.formatAward(item.award)
          }))
        } else {
          this.$message.error(response.message || '数据为空')
          this.competitionData = []
        }
      } catch (error) {
        this.$message.error('请求失败，请重试')
        console.error(error)
        this.competitionData = []
      } finally {
        this.loading = false
      }
    },
    // 格式化奖项等级
    formatAward(awardLevel) {
      const awardMap = {
        1: '一等奖',
        2: '二等奖',
        3: '三等奖'
      }
      return awardMap[awardLevel] || '未获奖'
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.selector-container {
  margin-bottom: 30px;
  display: flex;
  gap: 20px;
}

.autocomplete-item {
  padding: 10px;
  cursor: pointer;
  &:hover {
    background-color: #f5f7fa;
  }
}
</style>
